import getSign from './sign'
import { call } from './promise'
import { getInfo, setInfo } from './user'
const baseUrl = 'http://你的域名/api/'

Promise.prototype.finally = function (callback) {
  var Promise = this.constructor
  return this.then(
    function (value) {
      Promise.resolve(callback()).then(
        function () {
          return value
        }
      )
    },
    function (reason) {
      Promise.resolve(callback()).then(
        function () {
          throw reason
        }
      )
    }
  )
}

const http = ({ url = '', params = {}, method = 'GET' }) => {
  const request = baseUrl + url
  const token = getToken()
  params.timestamp = new Date().getTime()
  const sign = getSign(request, params)

  return new Promise((resolve, reject) => {
    wx.request({
      url: request,
      data: params,
      method: method,
      'header': {
        'content-type': 'application/json',
        'X-Token': token,
        'X-Sign': sign
      },
      complete: (res) => {
        if (res.statusCode > 200) {
          if (res.statusCode == 401) {
            login().then(res => {
              // http({ url, params, method }).then(res => {
              //   resolve(res.data);
              // })
              const router = getCurrentPages()
              router[router.length - 1].onShow()
            })
          } else {
            reject(res.data)
          }
        } else if (res.statusCode == 200) {
          if (res.data.code > 0) {
            reject(res.data)
          } else {
            resolve(res.data)
          }
        }
      },
      fail: function (res) {
        reject('网络连接错误')
      }
    })
  })
}

const get = (url, params = {}) => {
  return http({
    url,
    params
  })
}

const post = (url, params = {}) => {
  return http({
    url,
    params,
    method: 'POST'
  })
}

const getToken = () => {
  const info = getInfo()
  return info ? info.token : ''
}

const login = () => {
  return new Promise((resolve, reject) => {
    call('login').then(res => {
      const params = { code: res.code }
      call('getSetting').then(getSettingRes => {
        if (getSettingRes.authSetting['scope.userInfo']) {
          call('getUserInfo').then(getUserInfoRes => {
            params.info = getUserInfoRes.rawData
            params.signature = getUserInfoRes.signature
            params.encryptedData = encodeURIComponent(getUserInfoRes.encryptedData)
            params.iv = getUserInfoRes.iv
            params.invite = wx.getStorageSync('invite')// 邀请ID
            // 登录
            post('login', params).then(loginRes => {
              const data = loginRes.data
              setInfo(data)
              resolve(data)
            })
              .catch(error => {
                setInfo('')
                reject(error)
              })
          })
        } else {
          reject(res)
        }
      })
    })
      .catch(error => {
        reject(error)
      })
  })
}

module.exports = {
  baseUrl,
  get,
  post,
  login,
  getToken
}